<?php
/**
 * @author css3 <css3@qq.com>
 */

namespace zonday\weixin\api;

use Yii;
use yii\base\Object;

/**
 * Class Api
 */
class Api extends Object
{
    const API_BASE_URL = 'https://api.weixin.qq.com/cgi-bin';

    /**
     * @return \zonday\weixin\Weixin
     */
    protected $weixin;

    /**
     * @return \zonday\weixin\Weixin
     */
    public function getWeixin()
    {
        if (!isset($this->weixin)) {
            $this->weixin = Yii::$app->weixin;
        }
        return $this->weixin;
    }

    /**
     * @param \zonday\weixin\Weixin $weixin
     */
    public function setWeixin(\zonday\weixin\Weixin $weixin)
    {
        $this->weixin = $weixin;
    }

    /**
     * 获取自动回复规则
     * @return mixed
     */
    public function getCurrentAutoReplyInfo()
    {
        return $this->request('get_current_autoreply_info');
    }

    /**
     * 获取自定义菜单配置接口
     * @see http://mp.weixin.qq.com/wiki/17/4dc4b0514fdad7a5fbbd477aa9aab5ed.html
     * @return mixed
     */
    public function getCurrentSelfMenu()
    {
        return $this->request('get_current_selfmenu_info');
    }

    /**
     * 长链接转短链接
     * @see http://mp.weixin.qq.com/wiki/10/165c9b15eddcfbd8699ac12b0bd89ae6.html
     * @param string $longUrl
     * @param string $action
     * @return mixed
     */
    public function shortUrl($longUrl, $action = 'long2short')
    {
        return $this->request('shorturl', null, ['action' => $action, ['long_url' => $longUrl]]);
    }

    /**
     * @param $apiSubUrl
     * @param null $get
     * @param null $post
     * @param array $options
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \zonday\weixin\InvalidResponseException
     * @throws \zonday\weixin\exception\WeixinErrorException
     * @throws \zonday\weixin\exception\WeixinException
     */
    protected function request($apiSubUrl, $get = null, $post = null, $options = [])
    {
        if (preg_match('/^https?:\\/\\//is', $apiSubUrl)) {
            $url = $apiSubUrl;
        } else {
            $url = static::API_BASE_URL . '/' . $apiSubUrl;
        }

        $get['access_token'] = $this->getWeixin()->getAccessToken();
        $options = array_merge([
            'raw' => false,
            'jsonEncode' => true,
        ], $options);
        if (is_array($post) && $options['jsonEncode']) {
            $post = json_encode($post, JSON_UNESCAPED_UNICODE);
        }
        return $this->getWeixin()->request($url, $get, $post, $options['raw']);
    }

}
